import {getAppVersion} from "@/update/getUpdateInfo";

interface PackageInfo {
    title: string;
    contents: string;
    is_mandatory: boolean;
    url: string;
    platform: string;
    type: 'wgt' | 'pkg';
}

export function fCheckVersion(): void {
    // #ifdef APP-PLUS
    if (plus.runtime.appid != null) {
        plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
            const nVerSta = compare(plus.runtime.version, widgetInfo.version);
            let sLaststVer = plus.runtime.version;

            if (widgetInfo.version) {
                sLaststVer = nVerSta === 1 ? plus.runtime.version
                    : nVerSta === -1 ? widgetInfo.version
                        : sLaststVer;
            }

            const param = {
                versionCode: sLaststVer,
                platform: uni.getSystemInfoSync().platform
            };
            getAppVersion(param).then((resData: any) => {
                console.log('获取最新版本信息', resData);
                if (!resData.data) return;

                const [sUrl, type] = resData.wgtName
                    ? [resData.wgtName, 'wgt' as const]
                    : [resData.pkgName, 'pkg' as const];

                updateUseModal({
                    title: resData.title || "",
                    contents: resData.note || '',
                    is_mandatory: true,
                    url: sUrl || '',
                    platform: uni.getSystemInfoSync().platform,
                    type
                });
            }).catch((e) => {
                console.log('获取最新版本信息失败',e);
            })
        });
    }
    // #endif
}

function compare(v1: string = '0', v2: string = '0'): number {
    const v1Arr = v1.split('.').map(Number);
    const v2Arr = v2.split('.').map(Number);
    const minVersionLens = Math.min(v1Arr.length, v2Arr.length);

    let result = 0;
    for (let i = 0; i < minVersionLens; i++) {
        const curV1 = v1Arr[i];
        const curV2 = v2Arr[i];

        if (curV1 > curV2) return 1;
        if (curV1 < curV2) return -1;
    }

    if (result === 0 && v1Arr.length !== v2Arr.length) {
        const longerVersion = v1Arr.length > v2Arr.length ? v1Arr : v2Arr;
        for (let i = minVersionLens; i < longerVersion.length; i++) {
            if (longerVersion[i] > 0) {
                return v1Arr === longerVersion ? 1 : -1;
            }
        }
    }
    return result;
}

const updateUseModal = (packageInfo: PackageInfo): void => {
    const {
        title,
        contents,
        is_mandatory,
        url,
        platform,
        type
    } = packageInfo;

    const isWGT = type === 'wgt';
    const isiOS = !isWGT && platform.includes('ios');
    const confirmText = isiOS ? '立即跳转更新' : '立即下载更新';

    uni.showModal({
        title,
        content: contents,
        showCancel: !is_mandatory,
        confirmText,
        success: (res) => {
            if (res.cancel) return;

            if (isiOS) {
                plus.runtime.openURL(url);
            } else {
                plus.runtime.openURL(url);
            }

            const waiting = plus.nativeUI.showWaiting("正在下载 - 0%");
            const downloadTask = uni.downloadFile({
                url,
                success: (res) => {
                    if (res.statusCode !== 200) {
                        console.error('下载安装包失败', res);
                        return;
                    }

                    plus.runtime.install(res.tempFilePath, {
                        force: false
                    }, () => {
                        if (is_mandatory) {
                            plus.runtime.restart();
                            return;
                        }
                        uni.showModal({
                            title: '安装成功是否重启？',
                            success: (res) => {
                                if (res.confirm) {
                                    plus.runtime.restart();
                                }
                            }
                        });
                    }, (err) => {
                        uni.showModal({
                            title: '更新失败',
                            content: err.message,
                            showCancel: false
                        });
                    });
                },
                complete: () => {
                    waiting.close();
                    downloadTask.offProgressUpdate();
                }
            });

            downloadTask.onProgressUpdate((res) => {
                waiting.setTitle(`正在下载 - ${res.progress}%`);
            });
        }
    });
};